<script lang="tsx">
import { defineComponent, ref } from 'vue';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import { $t } from '@vben/locales';
import { usePage } from '#/hooks/page/usePage';
import { FileText, Pencil, Trash2, Send } from '@vben/icons';
import deleteIcon from '#/assets/images/delete-icon.png';
import EditDrawer from './modules/announcement/edit-drawer.vue';
import DetailDrawer from './modules/announcement/detail-drawer.vue';
import { getAnnouncementListApi, deleteAnnouncementApi, publishAnnouncementApi, getAnnouncementDetailApi, updateAnnouncementApi, createAnnouncementApi } from '#/api/system/announcement';

import { convertObsUrlsToKeys, convertKeysToObsUrls } from '#/utils/getImgUrl';

export default defineComponent({
  name: 'SystemAnnouncementPage',
  setup() {
    // 抽屉相关状态
    const showDrawer = ref(false);
    const drawerMode = ref<'add' | 'edit'>('add');
    const drawerFormData = ref<any>({}); // 抽屉表单数据
    const loading = ref(false) // 抽屉确定按钮loading
    const editDataLoading = ref(false) // 编辑数据获取loading

    // 详情抽屉相关状态
    const showDetailDrawer = ref(false);
    const currentAnnouncementId = ref<string | number>('');

    // API配置
    const API = {
      get: getAnnouncementListApi,
      delete: deleteAnnouncementApi,
    };

    // 表格列配置
    const columns = [
      { type: 'selection', width: 50, align: 'center', prop: '' },
      { prop: 'title', label: $t('announcement.announcementTitle'), minWidth: 150, showOverflowTooltip: true },
      {
        prop: 'publisher', label: $t('announcement.publisher'), minWidth: 120, showOverflowTooltip: true,
        formatter: (row: any) => {
          return (
            <span>
              {row.publisher || '--'}
            </span>
          );
        }
      },
      {
        prop: 'type',
        label: $t('announcement.announcementType'),
        minWidth: 100,
        formatter: (row: any) => {
          const typeMap: any = {
            'upgrade': $t('announcement.types.upgrade'),
            'system': $t('announcement.types.system'),
          };
          return (
            <span>
              {typeMap[row.type] || row.type || $t('announcement.unknown')}
            </span>
          );
        }
      },
      {
        prop: 'status',
        label: $t('announcement.status'),
        minWidth: 80,
        formatter: (row: any) => {
          const statusMap: any = {
            'pending': $t('announcement.statusTypes.pending'),
            'published': $t('announcement.statusTypes.published'),
          };
          const statusColors: any = {
            'pending': '#FB9A0E',
            'published': '#30A46C',
          };
          return (
            <span style="display: flex; align-items: center;">
              <span
                style={{
                  display: 'inline-block',
                  width: '8px',
                  height: '8px',
                  borderRadius: '50%',
                  marginRight: '6px',
                  background: statusColors[row.status] || '#ccc',
                }}
              ></span>
              {statusMap[row.status] || row.status || $t('announcement.unknown')}
            </span>
          );
        }
      },
      {
        prop: 'publishTime', label: $t('announcement.publishTime'), minWidth: 160, showOverflowTooltip: true,
        formatter: (row: any) => {
          return (
            <span>
              {row.publishTime || '--'}
            </span>
          );
        }
      },
      { prop: 'createTime', label: $t('announcement.addTime'), minWidth: 160, showOverflowTooltip: true },
    ];

    // 查询区配置
    const queryColumns = [
      { prop: 'title', label: $t('announcement.announcementTitle'), type: 'input', placeholder: $t('announcement.placeholders.searchInput') },
      { prop: 'publisher', label: $t('announcement.publisher'), type: 'input', placeholder: $t('announcement.placeholders.searchInput') },
      {
        prop: 'typeList',
        label: $t('announcement.announcementType'),
        type: 'select',
        placeholder: $t('announcement.placeholders.selectPlaceholder'),
        options: [
          { label: $t('announcement.types.upgrade'), value: 'upgrade' },
          { label: $t('announcement.types.system'), value: 'system' }
        ]
      },
      {
        prop: 'statusList',
        label: $t('announcement.status'),
        type: 'select',
        placeholder: $t('announcement.placeholders.selectPlaceholder'),
        options: [
          { label: $t('announcement.statusTypes.published'), value: 'published' },
          { label: $t('announcement.statusTypes.pending'), value: 'pending' }
        ]
      },
      {
        prop: 'publishTime',
        // label: $t('announcement.publishTime'),
        label: '发布开始',
        type: 'daterange',
        component: 'el-date-picker',
        rangeSeparator: $t('announcement.rangeSeparator'),
        unlinkPanels: true,
        startPlaceholder: $t('announcement.placeholders.startTime'),
        endPlaceholder: $t('announcement.placeholders.endTime'),
        format: "YYYY-MM-DD",
        'value-format': "YYYY-MM-DD HH:mm:ss",
        'default-time': [
          new Date(2000, 1, 1, 0, 0, 0),
          new Date(2000, 1, 1, 23, 59, 59),
        ],
        // style: { width: 'calc(50% - 7px)' },
        onChange: (val: any) => {
          changeDateRange(val, 'publishTime');
        }
      },
      {
        prop: 'addTime',
        label: $t('announcement.addTime'),
        type: 'daterange',
        component: 'el-date-picker',
        rangeSeparator: $t('announcement.rangeSeparator'),
        unlinkPanels: true,
        startPlaceholder: $t('announcement.placeholders.startTime'),
        endPlaceholder: $t('announcement.placeholders.endTime'),
        format: "YYYY-MM-DD",
        'value-format': "YYYY-MM-DD HH:mm:ss",
        'default-time': [
          new Date(2000, 1, 1, 0, 0, 0),
          new Date(2000, 1, 1, 23, 59, 59),
        ],
        // style: { width: 'calc(50% - 7px)' },
        onChange: (val: any) => {
          changeDateRange(val, 'addTime');
        }
      },
    ];

    // 操作按钮配置
    const commands = [
      {
        key: 'view',
        width: 40,
        icon: FileText,
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={$t('announcement.detail')}
            placement="top"
          >
            <el-button icon={FileText} link onClick={() => handleView(row)}></el-button>
          </el-tooltip>
        ),
      },
      {
        key: 'patch',
        width: 40,
        render: (row: any) => {
          return (
            <el-tooltip
              effect="dark"
              content={$t('common.pushTxt')}
              placement="top"
            >
              <el-button
                icon={Send}
                link
                disabled={row.status === 'published'}
                onClick={() => { handlePublic(row); }}
              ></el-button>
            </el-tooltip>
          );
        },
      },
      {
        key: 'delete',
        width: 40,
        label: $t('announcement.delete'),
        icon: Trash2,
      },
      {
        key: 'put',
        width: 40,
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={$t('common.editTxt')}
            placement="top"
          >
            <el-button
              icon={Pencil}
              link
              disabled={row.status === 'published'}
              onClick={() => handleEdit(row)}></el-button>
          </el-tooltip>
        ),
      },
    ];

    const deleteProps = {
      title: '',
      message: `
        <div style="display: flex; align-items: center;">
          <img src="${deleteIcon}" style="width: 48px; height: 48px; margin-right: 10px;" />
          <span>${$t('announcement.messages.deleteConfirm')}</span>
        </div>
      `,
      confirmButtonText: $t('common.confirm'),
      cancelButtonText: $t('common.cancel'),
      customClass: 'delete-dialog',
      dangerouslyUseHTMLString: true,
      center: false,
    };

    // 使用页面表格hooks
    const {
      render,
      getTableData,
      queryState,
    } = usePage({
      API,
      columns,
      queryColumns,
      commands,
      deleteProps,
    });

    // 添加时间选择器事件处理
    const changeDateRange = (val: any, field: string) => {
      if (val && val.length === 2) {
        if (field === 'publishTime') {
          queryState.data.publishStartTime = val[0]
          queryState.data.publishEndTime = val[1]
        } else if (field === 'addTime') {
          queryState.data.addStartTime = val[0]
          queryState.data.addEndTime = val[1]
        }
      } else {
        if (field === 'publishTime') {
          queryState.data.publishStartTime = ''
          queryState.data.publishEndTime = ''
        } else if (field === 'addTime') {
          queryState.data.addStartTime = ''
          queryState.data.addEndTime = ''
        }
      }
    };

    // 发布按钮事件
    const handlePublic = (row: any) => {
      ElMessageBox({
        title: $t('common.tipTxt'),
        message: $t('announcement.messages.publishConfirm'),
        showCancelButton: true,
        confirmButtonText: $t('common.confirm'),
        cancelButtonText: $t('common.cancel'),
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            publishAnnouncementApi(row.id).then(() => {
              done()
              ElMessage.success($t('announcement.messages.publishSuccess'));
              getTableData();
            }).finally(() => {
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        },
      })
    };

    // 新增按钮事件
    const handleAdd = () => {
      drawerMode.value = 'add';
      drawerFormData.value = {
        title: '',
        content: '<p><br></p>', // 为富文本编辑器提供默认内容
        type: '',
      };
      showDrawer.value = true;
    };

    // 查看按钮事件
    const handleView = (row: any) => {
      currentAnnouncementId.value = row.id;
      showDetailDrawer.value = true;
    };

    // 清理内容，移除可能导致编辑器冲突的HTML
    const cleanContentForEditor = (content: string): string => {
      if (!content) return '';

      try {
        // 移除可能导致Slate冲突的HTML标签和属性
        let cleaned = content
          // 移除data-slate-*属性
          .replace(/\s*data-slate-[^=]*="[^"]*"/g, '')
          // 移除data-key属性
          .replace(/\s*data-key="[^"]*"/g, '')
          // 移除contenteditable属性
          .replace(/\s*contenteditable="[^"]*"/g, '')
          // 移除wangEditor相关属性
          .replace(/\s*data-w-e-[^=]*="[^"]*"/g, '')
          // 移除可能的slate节点标记
          .replace(/\s*data-slate-node="[^"]*"/g, '')
          .replace(/\s*data-slate-inline="[^"]*"/g, '')
          .replace(/\s*data-slate-void="[^"]*"/g, '');

        return cleaned;
      } catch (error) {
        // console.warn('清理编辑器内容时出错:', error);
        return content;
      }
    };

    // 编辑按钮事件
    const handleEdit = async (row: any) => {
      drawerMode.value = 'edit';
      showDrawer.value = true;
      editDataLoading.value = true;

      try {
        const res = await getAnnouncementDetailApi(row.id);
        let { title, type, details, id } = { ...res };

        // 清理编辑器冲突的HTML
        let content = cleanContentForEditor(details);
        // console.log('编辑 - 清理后内容:', content);

        // 将key值转换为URL用于编辑器显示
        content = await convertKeysToObsUrls(content);
        // console.log('编辑 - 转换后内容:', content);

        drawerFormData.value = { title, type, content, id };
      } catch (error) {
        // console.error('获取公告详情失败:', error);
        ElMessage.error($t('announcement.messages.getDetailFailed'));
      } finally {
        editDataLoading.value = false;
      }
    };

    // 抽屉点击确认
    const handleDrawerConfirm = async (formData: any) => {
      loading.value = true;
      const paramData = { ...formData };

      try {
        // 将内容中的OBS URL转换为key值
        paramData.content = await convertObsUrlsToKeys(paramData.content);

        if (drawerMode.value === 'add') {
          await createAnnouncementApi(paramData).then(() => {
            ElMessage.success($t('announcement.messages.addSuccess'));
          });
        } else {
          await updateAnnouncementApi(paramData).then(() => {
            ElMessage.success($t('announcement.messages.editSuccess'));
          });
        }
        showDrawer.value = false;
        getTableData();
      } catch (error) {
        // console.error('保存公告失败:', error);
        ElMessage.error($t('announcement.messages.saveFailed'));
      } finally {
        loading.value = false;
      }
    };

    // 抽屉点击取消
    const handleDrawerCancel = () => {
      showDrawer.value = false;
    };

    // 详情抽屉编辑事件
    const handleDetailEdit = async (announcementData: any) => {
      drawerMode.value = 'edit';

      try {
        // 将key值转换为URL用于编辑器显示
        let content = await convertKeysToObsUrls(announcementData.content);

        drawerFormData.value = {
          title: announcementData.title,
          type: announcementData.type,
          content: content,
          id: announcementData.id
        };
        showDrawer.value = true;
      } catch (error) {
        // console.error('处理公告内容失败:', error);
        ElMessage.error($t('announcement.messages.processContentFailed'));
      }
    };

    return () => (
      <div>
        {render({
          header: (
            <ElButton type="primary" onClick={handleAdd}>
              {$t('common.addTxt')}
            </ElButton>
          ),
          table: {
            prefix: () => [] // 覆盖默认的 prefix，不包含 serialColumn
          }
        })}
        <EditDrawer
          modelValue={showDrawer.value}
          formData={drawerFormData.value}
          mode={drawerMode.value}
          loadFlag={loading.value}
          editDataLoading={editDataLoading.value}
          onUpdate:modelValue={val => showDrawer.value = val}
          onConfirm={handleDrawerConfirm}
          onCancel={handleDrawerCancel}
        />
        <DetailDrawer
          modelValue={showDetailDrawer.value}
          announcementId={currentAnnouncementId.value}
          onUpdate:modelValue={val => showDetailDrawer.value = val}
          onEdit={handleDetailEdit}
        />
      </div>
    );
  }
});
</script>
<style lang="scss" scoped>
:deep(.el-form--inline .el-form-item) {
  &:nth-of-type(6n) {
    margin-right: 0px;
  }
}
</style>
